package org.demo.mine.model;

import lombok.extern.log4j.Log4j2;
import org.demo.mine.util.ListHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * @Author:LiaoYouLe
 * @Date: Created in 2018/8/31
 * @Description
 * @Modifyied By:
 */
@Component
@Log4j2
public class BoxDashBoard {


    @Autowired
    private HttpSession httpSession;


    public ListHashMap<Integer, Box> getBoxArea() {
        ListHashMap<Integer, Box> datasource = (ListHashMap<Integer, Box>) httpSession.getAttribute("datasource");
        if (null == datasource) {
            datasource = init();
            httpSession.setAttribute("datasource", datasource);
        }
        return datasource;
    }

    private ListHashMap<Integer, Box> init() {
        return new DataSource().init();
    }

    public void reset() {
        httpSession.setAttribute("datasource", null);
    }


    static class DataSource {
        private int wigthLength = 10;

        private ListHashMap<Integer, Box> boxArea = new ListHashMap<>();

        private ListHashMap<Integer, Box> init() {
            Random random = new Random();
            Set<Integer> mineSeed = new HashSet<>(12);
            for (int j = 0; j < 12; ) {
                boolean result = mineSeed.add(random.nextInt(99) + 1);
                if (result) {
                    j++;
                }
            }

            for (int i = 1; i <= 100; i++) {
                Box box = Box.getInstance(i, false);
                if (mineSeed.contains(i)) {
                    box.setMine(true);
                }
                addGroundBox(box);
                boxArea.add(box);
            }
            return boxArea;
        }


        private void addGroundBox(Box box) {
            int id = box.getId();
            //上
            setBox(id - wigthLength, box);
            if (id % wigthLength != 1) {
                //左上
                setBox(id - wigthLength - 1, box);
                //左边
                setBox(id - 1, box);
            }
            if (id % wigthLength != 0) {
                //右上
                setBox(id - wigthLength + 1, box);
            }

        }

        private void setBox(int id, Box box) {
            Box groundBox = boxArea.getData(id);
            if (null != groundBox) {
                box.addGroundBox(groundBox);
                groundBox.addGroundBox(box);
            }
        }

    }


}
